/*
 * Singleton.h
 *
 *  Created on: 2008-8-12
 *      Author: fanliangliang
 */

#ifndef SINGLETON_H_
#define SINGLETON_H_

#include "config.h"

#ifdef SAFE_SINGLETON
#include "lock.h"
#define VOLATILE volatile
#else
#define VOLATILE
#endif /* SAFE_SINGLETON */

BEGIN_NAMESPACE_TOXIC

template<typename T>
class Singleton {
	CLASS_UNCOPYABLE(Singleton)
public:

#ifdef SAFE_SINGLETON
	static T* instance() {
		if (0 == _instance) {
			ScopedLock lock(_mutex);
			if (0 == _instance) {
				_instance = new T();
				atexit(destroy);
			}
		}
		return _instance;
	}
#else
	static T* instance() {
		if (0 == _instance) {
			_instance = new T();
			atexit(destroy);
		}
		return _instance;
	}
#endif /* SAFE_SINGLETON */

protected:
	Singleton() {}
	~Singleton() {}

public:
	static void destroy() {
		delete _instance;
		_instance = 0;
	}

#ifdef SAFE_SINGLETON
	static Mutex _mutex;
#endif /* SAFE_SINGLETON */

	static T* VOLATILE _instance;
};

#ifdef SAFE_SINGLETON
template<typename T>
Mutex Singleton<T>::_mutex;
#endif /* SAFE_SINGLETON */

template<typename T>
T* VOLATILE Singleton<T>::_instance = 0;

END_NAMESPACE_TOXIC

#endif /* SINGLETON_H_ */
